﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;

namespace mAdcOW.SharePoint.TaxonomyFilter.TaxonomyFilterWebPart
{
    public class TaxonomyFilter : ITransformableFilterValues
    {
        private string DummyValue
        {
            get { return "TaxonomyFilter" + _provider.ClientID; }
        }

        private readonly ITaxonomyFilterValueProvider _provider;

        public TaxonomyFilter(ITaxonomyFilterValueProvider provider)
        {
            _provider = provider;
            _provider.Load += ProviderLoad;
        }

        // In load looks for the connection between XsltListViewWebPart & Provider 
        // To register the subsequent DataBinding event. 
        private void ProviderLoad(object sender, EventArgs e)
        {
            foreach (WebPartConnection wpc in _provider.WebPartManager.Connections)
            {
                if (wpc.Provider == _provider && wpc.Consumer is XsltListViewWebPart)
                {
                    wpc.Consumer.DataBinding += XsltListViewWebPartDataBinding;
                    break;
                }
            }
        }

        // Search for the placeholders in the filter operations on XsltListViewWebPart 
        // And replaces it with the correct values ​​and the desired operation type. 
        private void XsltListViewWebPartDataBinding(object sender, EventArgs e)
        {
            if (!_provider.HasValue) return;
            XsltListViewWebPart xwp = (XsltListViewWebPart)sender;

            foreach (KeyValuePair<string, FilterOperation> operation in xwp.FilterOperations)
            {
                var filterOp = operation.Value;
                // Search for the DummyValue and replace it 
                if (filterOp.FilterValue != DummyValue) continue;
                filterOp.FilterValue = _provider.FilterValue;
                filterOp.IsFieldLookupId = true;
                filterOp.OperationType = "In";
                filterOp.FilterData = _provider.FilterData;
                break;
            }
        }

        public bool AllowAllValue
        {
            get { return true; }
        }

        public bool AllowEmptyValue
        {
            get { return true; }
        }

        public bool AllowMultipleValues
        {
            get { return true; }
        }

        public string ParameterName
        {
            get { return "Taxonomy filter"; }
        }

        public ReadOnlyCollection<string> ParameterValues
        {
            get
            {
                List<string> list = new List<string>();
                if (_provider.HasValue)
                {
                    list.Add(DummyValue);
                }
                return new ReadOnlyCollection<string>(list);
            }
        }
    }
}